<?php

namespace Beerus\Modules\DecoCompany\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use Beerus\Modules\DecoCompany\Actions\BindOperator;
use Beerus\Modules\DecoCompany\Actions\ModifyAuthTime;
use Beerus\Modules\DecoCompany\Actions\UnbindOperator;
use Doraemon\model\DecoCompany;
use Doraemon\model\DecoCompany\DecoCompanyAuditLog;
use Doraemon\model\DecoCompany\DecoCompanyServiceLog;
use Doraemon\model\DecoCompanyAuth;
use Doraemon\model\DecoCompanyPayService;
use Doraemon\model\DecoHouseScope;
use Doraemon\model\DecoMode;
use Doraemon\model\DecoServiceTag;
use Doraemon\model\Member;
use Doraemon\model\Operator;
use Doraemon\service\AreaCode\AreaCodeService;
use Doraemon\service\DecoCompany\DecoCompany as sDecoCompany;
use Doraemon\service\DecoCompany\PayService;
use Doraemon\service\User;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\ShopArea;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\DropdownActions;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Table;
use Hhz\AdministrativeRegion\Region;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\service\BusinessUser\EncryptPhone;
use hhz\constant\basic\UserExtendPhoneScene;

class AuthController
{
	public const PAGE_SIZE = 10;

	// 资料审核状态
	public const DATUM_STATUS_DESC = [
		DecoCompanyAuth::DATUM_PASS => '认证资料通过',
		DecoCompanyAuth::DATUM_REFUSE => '认证资料未通过',
	];

	public const TEST_ACCOUNT_OPTIONS = [
		DecoCompanyAuth::TEST_ACCOUNT_NO => '否',
		DecoCompanyAuth::TEST_ACCOUNT_YES => '是',
	];

	// 城市加载列表
	public static function cities(Request $request): array
	{
		$params = $request->all();

		$info = AreaCodeService::getCitiesByProvinces($params['q']);
		$data = [];
		foreach ($info[1] as $city_id => $city_name) {
			$data[] = [
				'id' => $city_id,
				'text' => $city_name
			];
		}

		return $data;
	}

	// 编辑
	public function index(Request $request, Content $content): Content
	{
		$params = $request->all();

		$page_size = $request->input('per_page', self::PAGE_SIZE);
		$page = $request->input('page', 1);

		$condition = [];
		if (!empty($params['uid'])) {
			$condition['uid'] = $params['uid'];
		}

		if (!empty($params['nick'])) {
			$uid = User::getUidByNick($params['nick']);
			$condition['uid'] = $uid;
		}

		if (!empty($params['enterprise_name'])) {
			$condition['enterprise_name'] = $params['enterprise_name'];
		}

		if (!empty($params['datum_status'])) {
			$condition['datum_status'] = $params['datum_status'];
		}

		if (!empty($params['submit_time']['start'])) {
			$condition['edittime[>=]'] = strtotime($params['submit_time']['start'] . ' 00:00:00');
		}

		if (!empty($params['submit_time']['end'])) {
			$condition['edittime[<=]'] = strtotime($params['submit_time']['end'] . ' 23:59:59');
		}
		if (!empty($params['operator_id'])) {
			$condition['admin_operator_id'] = $params['operator_id'];
		}

		$total = DecoCompanyAuth::count($condition);

		$lists = [];
		if ($total) {
			$condition['ORDER'] = ['edittime' => 'DESC'];
			$condition['LIMIT'] = [
				($page - 1) * $page_size,
				$page_size
			];

			$lists = DecoCompanyAuth::select('*', $condition);
			$user_ids = array_column($lists, 'uid');
			$member_info = Member::getUsers($user_ids);

			foreach ($lists as &$item) {
				$item['nick'] = empty($member_info[$item['uid']]['nick']) ? '' : $member_info[$item['uid']]['nick'];
				$item['user_type'] = Member::$typeDesc[$member_info[$item['uid']]['type']] ?? '-';
				$item['admin_operator_name'] = empty($item['admin_operator_id']) ? '' : Operator::getOperatorNameById($item['admin_operator_id']);
				$item['datum_status'] = DecoCompanyAuth::DATUM_STATUS[$item['datum_status']];
				$item['auth_status'] = DecoCompanyAuth::AUTH_STATUS_DESC[$item['auth_status']];

                $latest = DecoCompanyPayService::getLatestByUid($item['uid']);
                $item['latest_auth_time'] = $latest ? date('Y-m-d H:i:s', $latest['start_time']) : '-';
			}
			unset($item);
		}

		$operatorList = Operator::getOperatorWithShowNameList(Operator::OPERATOR_TYPE_DECO_COMPANY_BIND);
		$operators = array_combine(array_column($operatorList, 'id'), array_column($operatorList, 'operator_show_name'));
		$operators[0] = '未绑定运营';

		$gridModel = new pGridDataModel($lists, $total, [
			'perPage' => $page_size
		]);
		$gridList = Admin::grid($gridModel,
			function (Grid $grid) use ($gridModel, $operators) {
				$grid->setActionClass(DropdownActions::class);
				$grid->paginate($gridModel->getPerPage());
				$grid->disableExport();
				$grid->disableRowSelector();
				$grid->disableCreateButton();

				$grid->filter(function (Grid\Filter $filter) use ($operators) {
					$filter->disableIdFilter();
					$filter->column(1 / 3, function ($filter) {
						$filter->equal('uid', '用户UID')->placeholder('请输入uid');
					});
					$filter->column(1 / 3, function ($filter) {
						$filter->equal('nick', '用户昵称')->placeholder('请输入昵称');
					});
					$filter->column(1 / 3, function ($filter) {
						$filter->equal('enterprise_name', '公司名称')->placeholder('公司名称');
					});
					$filter->column(1 / 3, function ($filter) {
						$filter->equal('datum_status', '资料审核状态')->select(DecoCompanyAuth::DATUM_STATUS);
					});
					$filter->column(1 / 3, function ($filter) {
						$filter->between('submit_time', '提交资料时间')->date('Y-m-d');
					});
					$filter->column(1 / 3, function ($filter) use ($operators) {
						$filter->equal('operator_id', '对接运营')->checkbox($operators);
					});

					$filter->expand();
				});

				$grid->column('id', 'ID');
				$grid->column('addtime', '首次提交资料')->display(function () {
					return date('Y-m-d H:i:s', $this->addtime);
				});
				$grid->column('edittime', '最近一次提交资料')->display(function () {
					return date('Y-m-d H:i:s', $this->edittime);
				});
				$grid->column('uid', 'UID')->copyable();
				$grid->column('user_type', '当前身份');
				$grid->column('nick', '昵称')->copyable();
				$grid->column('enterprise_name', '公司名称')->copyable();
				$grid->column('city', '所在城市')->display(function () {
					return self::getAddressByAreaCode($this->city);
				});
				$grid->column('credit_code', '社会信用代码')->copyable();
				$grid->column('business_license_pic', '营业执照照片')->display(function () {
					return self::getUrl($this->business_license_pic);
				});
				$grid->column('hand_card_pic', '手持身份证照片')->display(function () {
					return self::getUrl($this->hand_card_pic);
				});
				$grid->column('missive', '申请公函')->display(function () {
					return self::getUrl($this->missive);
				});
				$grid->column('credentials', '资质证明')->display(function () {
					return self::getUrl($this->credentials);
				});
				$grid->column('datum_status', '资料审核状态')->display(function ($title, Grid\Column $column) {
					if ($this->datum_status === '审核通过') {
						return $column->label('success');
					}

					if ($this->datum_status === '用户撤回认证') {
						return $column->label('primary');
					}

					if ($this->datum_status === '审核不通过') {
						return $column->label('danger');
					}

					if ($this->datum_status === '审核中') {
						return $column->label('warning');
					}

					if ($this->datum_status === '待补充') {
						return $column->label('info');
					}

					return '';
				});
				$grid->column('auth_status', '认证状态')->display(function ($title, Grid\Column $column) {
					if ($this->auth_status === '已认证') {
						return $column->label('success');
					}

					if ($this->auth_status === '未认证') {
						return $column->label('primary');
					}

					if ($this->auth_status === '取消认证') {
						return $column->label('danger');
					}

					if ($this->auth_status === '认证过期') {
						return $column->label('warning');
					}

					return '';
				});
				$grid->column('admin_operator_name', '对接运营');
				$grid->column('admin_name', '审核人');
				$grid->column('admin_operate_time', '审核时间')->display(function () {
					return empty($this->admin_operate_time) ? '-' : date('Y-m-d H:i:s', $this->admin_operate_time);
				});
				$grid->column('latest_auth_time', '认证时间');
				$grid->column('auth_expire_time', '认证到期时间')->display(function () {
					return empty($this->auth_expire_time) ? '-' : date('Y-m-d H:i:s', $this->auth_expire_time);
				});
				$grid->column('is_test', '是否为测试号')->display(function () {
					return self::TEST_ACCOUNT_OPTIONS[$this->is_test];
				});

				$grid->actions(function (Grid\Displayers\Actions $actions) {
					$actions->disableDelete();
					//$actions->disableEdit();
					$actions->disableView();
					if ($actions->row['admin_operator_name'] === Admin::user()->username) {
						$actions->add(new UnbindOperator);
					} elseif ($actions->row['admin_operator_name'] === ''
						&& Operator::isOperatorByOperatorAdminName(Admin::user()->username, Operator::OPERATOR_TYPE_DECO_COMPANY_BIND)) {
						$actions->add(new BindOperator);
					}
					if (Admin::user()->isRole('deco_company_operation') && !PayService::isRenew($actions->row['uid'])) {
						$actions->add(new ModifyAuthTime());
					}

//		            if ($actions->row->auth_status == DecoCompanyAuth::DATUM_AUTH) {
//			            $actions->add(new AuditFail);
//			            $actions->add(new AuditPass);
//		            }
				});
			});

		$tab = new Tab();
		$tab->add('装修公司入驻认证列表', $gridList->render());
		$content->row($tab);
		return $content
			->header('装修公司入驻认证')
			->description(' ')
			->breadcrumb(['text' => '装修公司入驻认证']);
	}

	public static function getUrl(string $sPicIds)
	{
		if (empty($sPicIds)) {
			return '';
		}
		$aPicIds = explode(',', $sPicIds);
		$sImgUrls = '';
		foreach ($aPicIds as $sPicId) {
			$sImgUrl = ImgUrl::getBauthWaterUrl(ImgUrl::APPTYPE_BAUTH, $sPicId, ImgUrl::IMAGE_SIZE_SQ_THUMB, 60);
			$sImgUrls .= "<a style='display: inline-block; margin-bottom: 5px' href='{$sImgUrl}' target='_blank'><img style='box-shadow: 0 0 10px 0 rgba(0, 0, 0, .2)' width='100' height='100' src='{$sImgUrl}'></a>";
		}
		return $sImgUrls;
	}

	public function edit(Request $request, Content $content, $id, $tab_id): Content
	{
		$tab = new Tab();
		$tab_id = (int)$tab_id;
		$tab->addLink('基础信息', '/admin/DecoCompany/auth/' . $id . '/1', $tab_id === 1);
		$tab->addLink('认证图片', '/admin/DecoCompany/auth/' . $id . '/2', $tab_id === 2);
		$tab->addLink('服务信息', '/admin/DecoCompany/auth/' . $id . '/3', $tab_id === 3);
		$tab->addLink('审核历史记录', '/admin/DecoCompany/auth/' . $id . '/4', $tab_id === 4);
		$tab->addLink('认证服务记录', '/admin/DecoCompany/auth/' . $id . '/5', $tab_id === 5);

		$row = $this->basic($id, $tab_id);
		if ($tab_id === 2) {
			$row = $this->authPhotos($id, $tab_id);
		} elseif ($tab_id === 3) {
			$row = $this->serviceInfo($id, $tab_id);
		} elseif ($tab_id === 4) {
			$row = $this->auditHistory($id);
		} elseif ($tab_id === 5) {
			$row = $this->serviceRecord($id);
		}

		return $content
			->header('入驻信息详情')
			->breadcrumb([
				'text' => '装修公司入驻认证',
				'url' => route('auth.list'),
			], ['text' => '入驻信息详情'])
			->body($tab)
			->row($row);
	}

    public static function getAddressByAreaCode($area_code)
    {
        $address = '';
        if (!empty($area_code)) {
            $address = explode(',', $area_code);
            $province = Region::getNameByCode($address[0]);
            $city = Region::getNameByCode($address[1]);
            $area = Region::getNameByCode($address[2]);

            $address = $province . ' ' .$city . ' ' .$area;
        }

        return $address;
    }

	public function basic($id, $tab_id): string
	{
		$data = DecoCompanyAuth::get('*', ['id' => $id]);
		$data['city'] = self::getAddressByAreaCode($data['city']);
		$data['designer_team_size'] = DecoCompanyAuth::DESIGNER_TEAM_SIZE_DESC[$data['designer_team_size']] . ' 人';
		$data['tab_id'] = $tab_id;
		$data['founded_year'] .= ' 年';
		$data['auth_time'] = empty($data['auth_time']) ? '-' : date('Y-m-d H:i:s', $data['auth_time']);
		$data['auth_expire_time'] = empty($data['auth_expire_time']) ? '-' : date('Y-m-d H:i:s', $data['auth_expire_time']);
		$data['auth_status'] = DecoCompanyAuth::AUTH_STATUS_DESC[$data['auth_status']];

		$form = new Form($data);
		$form->hidden('id');
		$form->hidden('tab_id');
		$form->display('uid', '用户UID')->setWidth(3, 2);
		$form->display('auth_status', '账号认证状态')->setWidth(3, 2);
		$form->display('auth_time', '认证时间')->setWidth(3, 2);
		$form->display('auth_expire_time', '认证到期时间')->setWidth(3, 2);
		$form->display('enterprise_name', '公司名称')->setWidth(3, 2);
		$form->display('credit_code', '统一社会信用代码')->setWidth(3, 2);
		$form->display('founded_year', '公司成立年份')->setWidth(3, 2);
		$form->display('registered_capital', '注册资金（万元）')->setWidth(3, 2);
		$form->display('designer_team_size', '设计师数量（人）')->setWidth(3, 2);
		$form->display('city', '所在城市')->setWidth(3, 2);
		$form->text('operator_name', '账号运营人员姓名')->setWidth(3, 2);
		$form->mobile('operator_phone', '手机号')->setWidth(3, 2);
		$form->text('operator_wechat', '微信号')->setWidth(3, 2);
		$form->imgUpload('business_license_pic', '营业执照照片', false, [
			'imgType' => ImgUrl::APPTYPE_BAUTH,
			'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG,
		])->setWidth(3, 2);
		$form->imgUpload('hand_card_pic', '手持身份证照片', false, [
			'imgType' => ImgUrl::APPTYPE_BAUTH,
			'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG,
		])->setWidth(3, 2);
		$form->imgUpload('credentials', '装修、施工资质证明', false, [
			'imgType' => ImgUrl::APPTYPE_BAUTH,
			'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG,
		])->setWidth(3, 2);
		$form->imgUpload('missive', '申请公函照片', true, [
			'imgType' => ImgUrl::APPTYPE_BAUTH,
			'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG,
		])->setWidth(3, 2);

		$datum_status_desc = self::DATUM_STATUS_DESC;
		if (!in_array((int)$data['datum_status'], [DecoCompanyAuth::DATUM_PASS, DecoCompanyAuth::DATUM_REFUSE], true)) {
			$datum_status_desc[$data['datum_status']] = DecoCompanyAuth::DATUM_STATUS[$data['datum_status']];
		}
		$form->select('datum_status', '资料审核状态')->setWidth(3, 2)->options($datum_status_desc)
			->when(DecoCompanyAuth::DATUM_REFUSE, function ($form) {
				$form->select('reason', '审核未通过理由')->setWidth(3, 2)->options(DecoCompanyAuth::AUDIT_FAIL_REASON);
			})->required('必须选择');
		$form->select('is_test', '是否为测试号')->setWidth(3, 2)->options(self::TEST_ACCOUNT_OPTIONS)->required('必须选择');
		$form->textarea('remark', '备注')->setWidth(5, 2);
		$form->disableReset();

		$form->confirm('确认操作审核吗？');

		$form->action('/admin/DecoCompany/auth/save');
		return $form->render();
	}

	public function authPhotos($id, $tab_id): string
	{
		$data = DecoCompanyAuth::get('*', ['id' => $id]);
		$data['city'] = self::getAddressByAreaCode($data['city']);
		$data['designer_team_size'] = DecoCompanyAuth::DESIGNER_TEAM_SIZE_DESC[$data['designer_team_size']] . '人';
		$data['tab_id'] = $tab_id;
		$form = new Form($data);
		$form->hidden('id');
		$form->hidden('tab_id');

		$form->imgUpload('business_license_pic', '营业执照照片', false, [
			'imgType' => ImgUrl::APPTYPE_BAUTH,
			'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG,
		])->setWidth(3, 2);
		$form->imgUpload('hand_card_pic', '手持身份证照片', false, [
			'imgType' => ImgUrl::APPTYPE_BAUTH,
			'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG,
		])->setWidth(3, 2);
		$form->imgUpload('credentials', '装修、施工资质证明', false, [
			'imgType' => ImgUrl::APPTYPE_BAUTH,
			'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG,
		])->setWidth(3, 2);
		$form->imgUpload('missive', '申请公函照片', true, [
			'imgType' => ImgUrl::APPTYPE_BAUTH,
			'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG,
		])->setWidth(3, 2);
		$form->disableReset();
		$form->disableSubmit();

		$form->action('/admin/DecoCompany/auth/save');

		return $form->render();
	}

	public function serviceInfo($id, $tab_id): string
	{
		$auth_info = DecoCompanyAuth::getById($id);
		$data = DecoCompany::get('*', [
			'uid' => $auth_info['uid']
		]);
		$data['tab_id'] = $tab_id;
		$data['uid'] = $auth_info['uid'];
		$data['id'] = $auth_info['id'];
		$data['old_main_area_code'] = $data['main_area_code'];

		if (empty($data['service_price'])) {
			$data['service_price'] = '未填写';
		} else {
			$service_price = json_decode($data['service_price'], true);
			$data['service_price'] = $service_price['avg_min_price'] . ' ~ ' . $service_price['avg_max_price'];
		}

		$data['province'] = substr($data['main_area_code'], 0, 2) . '0000';
		$data['city'] = $data['main_area_code'];

		[$provinces, $cities] = AreaCodeService::getCitiesByProvinces($data['province']);

		$form = new Form($data);
		$form->hidden('id');
		$form->hidden('tab_id');
		$form->hidden('uid');
		$form->hidden('old_main_area_code');
		$form->checkbox('deco_mode', '装修方式')->options(function () {
			$lists = DecoMode::select(['id', 'name'], [
				'data_status' => DecoMode::STATUS_NORMAL,
				'ORDER' => [
					'weight' => 'DESC'
				]
			]);
			return array_column($lists, 'name', 'id');
		})->stacked();
		$form->checkbox('deco_house_scope', '装修房屋范围')->options(function () {
			$lists = DecoHouseScope::select(['id', 'name'], [
				'data_status' => DecoHouseScope::STATUS_NORMAL,
				'ORDER' => [
					'weight' => 'DESC'
				]
			]);
			return array_column($lists, 'name', 'id');
		})->stacked();
		$form->checkbox('service_tag', '服务标签')->options(function () {
			$lists = DecoServiceTag::select(['id', 'name'], [
				'data_status' => DecoServiceTag::STATUS_NORMAL,
				'ORDER' => [
					'weight' => 'DESC'
				]
			]);
			return array_column($lists, 'name', 'id');
		})->stacked();
		$form->display('service_price', '费用均价（万元）')->setWidth(2, 2);
		$form->select('province', '服务城市')->options($provinces)
			->setWidth(2, 2)
			->load('city', '/admin/DecoCompany/cities')->required();
		$form->select('city', '')->options($cities)->setWidth(2, 2)->required();
		$form->textarea('profile', '公司介绍')->setWidth(4, 2)->readonly();

		$form->disableReset();
		$form->confirm('确认修改服务城市吗？');
		$form->action('/admin/DecoCompany/auth/saveServiceInfo');

		return $form->render();
	}

	public function auditHistory($id): string
	{
		$auth_info = DecoCompanyAuth::getById($id);
		$lists = DecoCompanyAuditLog::select(['op_log', 'add_time', 'admin_name'], [
			'uid' => $auth_info['uid'],
			'ORDER' => [
				'id' => 'DESC'
			]
		]);

		$info = [];
		if (!empty($lists)) {
			foreach ($lists as $item) {
				$op_log = json_decode($item['op_log'], true);
				$info[] = [
					'op' => $op_log['op'],
					'reason' => $op_log['reason'] ?? '-',
					'add_time' => $item['add_time'],
					'admin_name' => $item['admin_name']
				];
			}
		}

		return (new Table(['操作', '理由', '审核时间', '审核人'], $info))->render();
	}

	/**
	 * 认证资料审核提交
	 */
	public function save(Request $request)
	{
		$params = $request->all();
		if ((int)$params['datum_status'] === DecoCompanyAuth::DATUM_REFUSE && empty($params['reason'])) {
			$error = new MessageBag([
				'title' => '请选择审核不通过的理由'
			]);
			return back()->withInput()->with(compact('error'));
		}
		$auth_info = DecoCompanyAuth::getById($params['id']);
		//处理手机号加密业务
        $operatorPhoneId = 0;
        if (isset($params['operator_phone'])){
            $operatorPhoneId = EncryptPhone::getEncryptPhoneId($params['operator_phone'],UserExtendPhoneScene::DECO_AUTH_OPERATE_PHONE);
        }
		$data = [
			'operator_name' => $params['operator_name'],
			//'operator_phone' => $params['operator_phone'],
			'operator_wechat' => $params['operator_wechat'],
			'datum_status' => $params['datum_status'],
			'business_license_pic' => $params['business_license_pic'],
			'hand_card_pic' => $params['hand_card_pic'],
			'missive' => $params['missive'],
			'credentials' => $params['credentials'],
			'reason' => $params['reason'],
			'remark' => $params['remark'],
			'is_test' => $params['is_test'],
			'admin_id' => Admin::user()->id,
			'admin_name' => Admin::user()->username,
			'admin_operate_time' => time(),
            'encrypt_operator_id' => $operatorPhoneId,
		];

		$id = $params['id'];

		$rs = DecoCompanyAuth::updateInfoById($id, $data);

		if ($rs) {
			$op_log = [
				'op' => DecoCompanyAuth::DATUM_STATUS[$data['datum_status']],
			];
			if ((int)$data['datum_status'] === DecoCompanyAuth::DATUM_REFUSE) {
				$op_log['reason'] = $data['reason'] ?? '';
			}

			// 成功回调
			if ((int)$auth_info['datum_status'] !== DecoCompanyAuth::DATUM_REFUSE
				&& (int)$data['datum_status'] === DecoCompanyAuth::DATUM_REFUSE) {
				// 审核不通过
				sDecoCompany::afterAuth($auth_info['uid'], [
					'type' => 'auth',
					'datum_status' => DecoCompanyAuth::DATUM_REFUSE,
					'auth_status' => $auth_info['auth_status'],
					'reason' => $data['reason'],
				]);
				DecoCompanyAuditLog::insert([
					'uid' => $auth_info['uid'],
					'op_log' => json_encode($op_log),
					'admin_id' => Admin::user()->id,
					'admin_name' => Admin::user()->username
				]);
			} else if ((int)$auth_info['datum_status'] !== DecoCompanyAuth::DATUM_PASS
				&& (int)$data['datum_status'] === DecoCompanyAuth::DATUM_PASS) {
				// 审核通过
				sDecoCompany::afterAuth($auth_info['uid'], [
					'type' => 'auth',
					'datum_status' => DecoCompanyAuth::DATUM_PASS,
					'auth_status' => $auth_info['auth_status'],
					'reason' => $data['reason'],
				]);
				DecoCompanyAuditLog::insert([
					'uid' => $auth_info['uid'],
					'op_log' => json_encode($op_log),
					'admin_id' => Admin::user()->id,
					'admin_name' => Admin::user()->username
				]);
			} elseif ((int)$data['datum_status'] === DecoCompanyAuth::DATUM_PASS) {
				sDecoCompany::afterAuth($auth_info['uid'], [
					'type' => 'info',
				]);
			}

			$success = new MessageBag([
				'title' => '修改成功'
			]);
			return redirect("/admin/DecoCompany/auth/{$id}/{$params['tab_id']}")->with(compact('success'));
		}

		$error = new MessageBag([
			'title' => '修改失败'
		]);
		return back()->withInput()->with(compact('error'));
	}

	public function saveServiceInfo(Request $request)
	{
		$params = $request->all();

		$city = (int)$params['city'];

		if ($city !== (int)$params['old_main_area_code']) {
			$main_area_name = Region::getNameByCode($city) ?? '';
			$old_city = Region::getOldCodeByCode($params['city']) ?? '';
			if (in_array((int)$params['province'], AreaCodeService::SPECIAL_AREA, true)) {
				$old_province = $old_city;
			} else {
				$old_province = Region::getOldCodeByCode($params['province']) ?? '';
			}

			$main_area = $old_province . ',' . $old_city;
			DecoCompany::update([
				'main_area' => $main_area,
				'main_area_code' => $city,
				'main_area_name' => $main_area_name,
			], [
				'uid' => $params['uid']
			]);

			$deco_company = DecoCompany::get('*', [
				'uid' => $params['uid']
			]);
			sDecoCompany::esSync($params['uid'], [
				'main_area_name' => $main_area_name,
				'is_show' => $deco_company['is_show'],
				'from' => DecoCompanyServiceLog::FROM_MANAGE
			]);

			// 记录修改日志
			DecoCompanyServiceLog::insert([
				'uid' => $params['uid'],
				'info' => json_encode([
					'main_area' => $main_area,
					'old_main_area_code' => $params['old_main_area_code'],
					'main_area_code' => $city,
					'main_area_name' => $main_area_name,
				]),
				'from' => DecoCompanyServiceLog::FROM_MANAGE,
				'admin_id' => Admin::user()->id,
				'admin_name' => Admin::user()->username
			]);
		}

		$success = new MessageBag([
			'title' => '服务城市修改成功'
		]);
		return redirect("/admin/DecoCompany/auth/{$params['id']}/{$params['tab_id']}")->with(compact('success'));
	}

	// 认证服务记录
	public function serviceRecord($id): string
	{
		$auth_info = DecoCompanyAuth::getById($id);
		$lists = DecoCompanyPayService::listByCondition([
			'uid' => $auth_info['uid'],
			'ORDER' => [
				'end_time' => 'DESC'
			],
		]);

		$info = [];
		foreach ($lists as $item) {
			$row = [
				'id' => $item['id'],
				'dsn' => $item['dsn'],
				'uid' => $item['uid'],
				'package_id' => $item['package_id'],
				'package_name' => $item['package_name'],
				'start_time' => date('Y-m-d H:i:s', $item['start_time']),
				'end_time' => date('Y-m-d H:i:s', $item['end_time']),
				'service_type' => DecoCompanyPayService::SERVICE_TYPE_TEXT[$item['service_type']],
				'service_status' => DecoCompanyPayService::SERVICE_STATUS_TEXT[$item['service_status']],
				'add_time' => empty($item['add_time']) ? '-' : date('Y-m-d H:i:s', $item['add_time']),
				'edit_time' => empty($item['edit_time']) ? '-' : date('Y-m-d H:i:s', $item['edit_time']),
			];
			$info[] = $row;
		}

		return (new Table(['ID', '订单DSN', '用户UID', '套餐ID', '套餐名称', '服务开始时间', '服务结束时间', '服务类别', '服务状态', '创建时间', '更新时间'], $info))->render();
	}
}
